﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Web;
using FaWorks.WebSocket.Entity.Message;

namespace FaWorks.WebSocket.Service
{
    public class MessageManager
    {
        private static IDictionary<string, Conversation> _conversations =
            new Dictionary<string, Conversation>();

        public static IMessageCallback CreateMessageCallback(OperationContext context) {
            //获取传进的消息属性
            MessageProperties properties = context.IncomingMessageProperties;
            //获取消息发送的远程终结点IP和端口
            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

            string sessionID = endpoint.Address;
            if (_sessions.Keys.Contains(sessionID)) {
                return _sessions[sessionID];
            }

            IMessageCallback callback = context.GetCallbackChannel<IMessageCallback>();
            context.Channel.Opened += delegate
            {
                
            };
            context.Channel.Closing += delegate 
            {
                lock (_sessions)
                {
                    if (_sessions.Keys.Contains(sessionID))
                    {
                        _sessions.Remove(sessionID);
                    }
                }
            };
            _sessions.Add(sessionID, callback);
            return callback;
        }

        public static void Brocast(string message) {
            lock (_sessions)
            {
                foreach (IMessageCallback cb in _sessions.Values)
                {
                    cb.Send(CreateMessage(message));
                }
            }
        }

        private static Message CreateMessage(string content)
        {
            Message message = ByteStreamMessage.CreateMessage(
                    new ArraySegment<byte>(
                        Encoding.UTF8.GetBytes(content)));
            message.Properties["WebSocketMessageProperty"] =
                    new WebSocketMessageProperty { MessageType = WebSocketMessageType.Text };

            return message;
        }
    }
}